package com.mano.mall.gateway.handler.factory;


import com.alibaba.fastjson.JSONObject;
import com.mano.mall.api.dto.gatewayhandler.output.GatewayHandlerOutputDTO;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.utils.SpringContextUtil;
import com.mano.mall.gateway.feign.GatewayHandlerServiceFeign;
import com.mano.mall.gateway.handler.GatewayHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 使用工厂获取Handler
 */
@Component
@Slf4j
public class FactoryHandler {

	@Autowired
	private GatewayHandlerServiceFeign gatewayHandlerServiceFeign;

	// 减少后续的数据操作，没有必要放redis,内存即可，如果要以后修改了顺序，则开个接口刷新即可
	private GatewayHandler firstGatewayHandler;

	/**
	 * 责任链启动方式：
	 * 
	 * 1.将每一个Handler存放到集合中实现遍历
	 * 
	 * @return
	 */
	public GatewayHandler getHandler() {

		if(null != this.firstGatewayHandler){
			return this.firstGatewayHandler;
		}

		log.info(">>>>>从数据库中获取最新的Handler开始<<<<<<<<<<<<<<<<<<");
		// 1.数据库查询第一个Handler
		BaseResponse<List<GatewayHandlerOutputDTO>> baseResponse = gatewayHandlerServiceFeign.getGWHandlerList();
		if (null == baseResponse.getData()) {
			return null;
		}

		// 获取 handler 列表，已经有序
		List<GatewayHandlerOutputDTO> handlers = (List<GatewayHandlerOutputDTO>) baseResponse.getData();

		GatewayHandler currentHandler = null;
		for(int i=0;i<handlers.size();i++){
			GatewayHandlerOutputDTO gatewayHandlerOutputDTO = handlers.get(i);
			GatewayHandler gatewayHandler = (GatewayHandler) SpringContextUtil.getBean(gatewayHandlerOutputDTO.getHandlerId());

			if(i == 0){
				firstGatewayHandler = currentHandler = gatewayHandler;
				continue;
			}
			currentHandler.setNextHandler(gatewayHandler);
			currentHandler = gatewayHandler;
		}
		// 3.直接把第一个Handler 放入到缓存中..
		log.info(">>>>>从数据库中获取最新的Handler结束<<<<<<<<<<<<<<<<<<");
		this.firstGatewayHandler = firstGatewayHandler;
		return firstGatewayHandler;

	}

}
